<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ESP32 开发辅助工具</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/themes/prism-tomorrow.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="assets/styles.css" rel="stylesheet" />
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gradient-to-br from-gray-900 to-gray-800 text-white min-h-screen">
    <div id="app" class="container mx-auto px-4 py-8">
        <!-- 应用将在此处渲染 -->
    </div>

    <!-- 模态框容器 -->
    <div id="modal-container"></div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/components/prism-core.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/plugins/autoloader/prism-autoloader.min.js"></script>
    
    <!-- 直接引用源文件 -->
    <script type="module">
        import { AppState } from './utils/state.js';
        import { UIManager } from './utils/ui-manager.js';
        import { CodeGenerator } from './utils/code-generator.js';
        import { FileExporter } from './utils/file-exporter.js';
        import { SerialManager } from './utils/serial-manager.js';

        class ESP32DevTool {
            constructor() {
                this.state = new AppState();
                this.ui = new UIManager(this.state);
                this.codeGenerator = new CodeGenerator(this.state);
                this.fileExporter = new FileExporter(this.state);
                this.serialManager = new SerialManager(this.state);
                
                this.init();
            }

            init() {
                // 初始化应用
                this.ui.init();
                this.bindEvents();
                this.loadSavedConfig();
                
                console.log('ESP32开发辅助工具已初始化');
            }

            bindEvents() {
                // 绑定UI事件
                this.ui.on('chipChange', (value) => {
                    this.state.setChipModel(value);
                    this.ui.updatePinDiagram();
                    this.debounceGenerateCode();
                });

                this.ui.on('projectNameChange', (value) => {
                    this.state.setProjectName(value);
                    this.debounceGenerateCode();
                });

                this.ui.on('featureToggle', (features) => {
                    this.state.setFeatures(features);
                    this.debounceGenerateCode();
                });

                this.ui.on('pinConfig', (pin, mode) => {
                    this.state.setPinConfig(pin, mode);
                    this.ui.updatePinDiagram();
                    this.debounceGenerateCode();
                });

                this.ui.on('generateCode', () => {
                    this.generateCode();
                });

                this.ui.on('downloadProject', () => {
                    this.fileExporter.downloadProject();
                });

                this.ui.on('exportText', () => {
                    this.fileExporter.exportProjectStructure();
                });

                this.ui.on('connectDevice', async () => {
                    try {
                        await this.serialManager.connect();
                        this.ui.updateConnectionStatus(true);
                    } catch (error) {
                        this.ui.showAlert('连接设备失败: ' + error.message, 'error');
                    }
                });

                this.ui.on('disconnectDevice', async () => {
                    try {
                        await this.serialManager.disconnect();
                        this.ui.updateConnectionStatus(false);
                    } catch (error) {
                        this.ui.showAlert('断开连接时出错: ' + error.message, 'error');
                    }
                });

                this.ui.on('flashFirmware', async (file) => {
                    if (!file) {
                        this.ui.showAlert('请选择固件文件', 'error');
                        return;
                    }
                    
                    try {
                        await this.serialManager.flashFirmware(file);
                        this.ui.showAlert('固件烧录成功！', 'success');
                    } catch (error) {
                        this.ui.showAlert('烧录失败: ' + error.message, 'error');
                    }
                });
            }

            debounceGenerateCode() {
                clearTimeout(this.debounceTimer);
                this.debounceTimer = setTimeout(() => {
                    this.generateCode();
                }, 500);
            }

            generateCode() {
                try {
                    const files = this.codeGenerator.generateProject();
                    this.state.setProjectFiles(files);
                    this.ui.updateCodePreview(files['main/main.c']);
                    this.ui.updateFileStructure();
                    this.ui.showAlert('代码生成完成', 'success');
                } catch (error) {
                    this.ui.showAlert('代码生成失败: ' + error.message, 'error');
                }
            }

            loadSavedConfig() {
                const savedConfig = localStorage.getItem('esp32_config');
                if (savedConfig) {
                    try {
                        const config = JSON.parse(savedConfig);
                        this.state.loadConfig(config);
                        this.ui.loadConfig(config);
                    } catch (e) {
                        console.error('加载配置时出错:', e);
                    }
                }
            }
            
            // 提供全局访问方法
            openPinConfigModal(pin) {
                this.ui.openPinConfigModal(pin);
            }
        }

        // 应用初始化
        document.addEventListener('DOMContentLoaded', () => {
            window.esp32DevTool = new ESP32DevTool();
        });
    </script>
</body>
</html>